﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace winApp2
{
    public partial class Form5 : Form
    {
        public Form5()
        {
            InitializeComponent();
            this.FormClosed += Form5_FormClosed;
        }

        void Form5_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (thread != null)
            {
                if (thread.ThreadState == ThreadState.Running)
                {
                    thread.Abort();
                }
            }
        }

        private void Form5_Load(object sender, EventArgs e)
        {
            DataTable dt = DB.GetTable("master", "select name from sysdatabases where dbid>4");
            cbDB.DisplayMember = "name";
            cbDB.DataSource = dt;//绑定DataTable
        }
        List<DataInfo> list = null;
        private void cbDB_SelectedIndexChanged(object sender, EventArgs e)
        {
            string db = cbDB.Text;
            //查询库的表
            string sql = "select name,xtype from sysobjects where xtype='u' or xtype='v' order by name, xtype";
            DataTable dt = DB.GetTable(db, sql);
            list = new List<DataInfo>();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                list.Add(new DataInfo
                {
                    TbName = MakeTbName(dt.Rows[i][0].ToString()),
                    Type = dt.Rows[i][1].ToString().Trim().ToLower() == "u" ? "表" : "视图"
                });
            }
            dataGridView1.DataSource = list;
            checkBox1.Checked = checkBox2.Checked = false;
        }

        private string MakeName(string p)
        {
            if (p.Length > 3)
            {
                return p.Substring(0, 3).ToLower() + p.Substring(3);
            } 
            return p.ToLower();
        }
        private string MakeTbName(string p)
        {

            return p.Substring(0, 1).ToUpper() + p.Substring(1);

        }


        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            dataGridView1.DataSource = null;
            CheckBox cbx = sender as CheckBox;
            foreach (var it in list)
            {
                if (it.Type == cbx.Text)
                {
                    it.IsSelected = cbx.Checked;
                }
            }
            dataGridView1.DataSource = list;
        }

        Thread thread = null;
        private void button1_Click(object sender, EventArgs e)
        {
            button2.Visible = false;
            if (label2.Text.Length == 0)
            {
                if (fdlg.ShowDialog() == DialogResult.OK)
                {
                    button2.Visible = true;
                    label2.Text = fdlg.SelectedPath;
                    thread = new Thread(new ThreadStart(MakeCode));
                    thread.Start();
                    //MakeCode();
                }
            }

        }

        private void MakeCode()
        {
            foreach (var it in list)
            {
                if (it.IsSelected)
                {

                    //获取库名
                    string db = cbDB.Text;
                    //查询表的前100行数据
                    string sql = "sp_columns '" + it.TbName + "'";
                    var dt1 = DB.GetTable(db, sql);
                    var dt2 = DB.GetTable(db, "sp_pkeys '" + it.TbName + "'");
                    List<string> keys = new List<string>();
                    for (int i = 0; i < dt2.Rows.Count; i++)
                    {
                        keys.Add(dt2.Rows[i]["COLUMN_NAME"].ToString().ToLower());
                    }
                    StreamWriter sw = new StreamWriter(label2.Text + "\\" + it.TbName + ".java", false, Encoding.UTF8);
                    StringBuilder sb = new StringBuilder();
                    sw.WriteLine(Fmt("package {0};", txtPackage.Text));
                    sw.WriteLine();
                    sw.WriteLine("\n\nimport org.nutz.dao.entity.annotation.*;");
                    sw.WriteLine("import java.sql.*;");
                    sw.WriteLine();
                    

                    sw.WriteLine(Fmt("@Table(\"{0}\")", it.TbName));
                    sw.Write(Fmt("public class {0} ", it.TbName));
                    sw.WriteLine("{");
                    for (int i = 0; i < dt1.Rows.Count; i++)
                    {
                        var name = dt1.Rows[i]["COLUMN_NAME"].ToString();
                        var type = dt1.Rows[i]["TYPE_NAME"].ToString().ToLower();
                        var outType = getType(type);
                        var privateName = MakeName(name);
                        if (keys.Contains(name.ToLower()))
                        {
                            sw.WriteLine("\t@Id");
                        }
                        else
                        {
                            sw.WriteLine("\t@Column");
                        }
                        sw.WriteLine("\tprivate " + outType + " " + privateName + ";");
                    }
                    sw.WriteLine();
                    for (int i = 0; i < dt1.Rows.Count; i++)
                    {
                        var name = dt1.Rows[i]["COLUMN_NAME"].ToString();
                        var type = dt1.Rows[i]["TYPE_NAME"].ToString().ToLower();
                        var outType = getType(type);
                        var privateName = MakeName(name);
                        var getName = "get" + MakeTbName(privateName);
                        var setName = "set" + MakeTbName(privateName);
                        sw.WriteLine("\tpublic "+outType+" "+getName+"() {");
                        sw.WriteLine("\t\treturn "+privateName+";");
                        sw.WriteLine("\t}");
                        sw.WriteLine();
                        sw.WriteLine("\tpublic void "+setName+"("+outType+" "+privateName+") {");
                        sw.WriteLine("\t\tthis."+privateName+" = "+privateName+";");
                        sw.WriteLine("\t}");
                        sw.WriteLine();

                    }
                     sw.WriteLine("}");


                    sw.Close();
                    label3.Text = "生成(" + it.Type + "):" + it.TbName;
                    label3.Refresh();
                    Thread.Sleep(10);
                }

            }
            label3.Text = "生成完毕.";
            label3.Refresh();
            thread = null;
        }

        private string getType(string type)
        {
            if (type.Contains("int")) return "Integer";
            if (type.StartsWith("real")) return "Double";
            if (type.StartsWith("float")) return "Double";
            if (type.StartsWith("money")) return "Double";
            if (type.StartsWith("numeric")) return "Double";
            if (type.StartsWith("datetime")) return "Timestamp";
            if (type.StartsWith("timestamp")) return "Timestamp";
            if (type.StartsWith("date")) return "Date";
            if (type.StartsWith("time")) return "time";
            if (type.StartsWith("decimal")) return "Double";

            if (type.StartsWith("image")) return "byte[]";
            if (type.StartsWith("binary")) return "byte[]";

            return "String";
        }

        private string Fmt(string f1, params object[] objs)
        {
            return string.Format(f1, objs);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            label2.Text = "";
            button2.Visible = false;
        }
    }


}
public class DataInfo
{
    public bool IsSelected { get; set; }
    public string TbName { get; set; }
    public string Type { get; set; }
}